﻿using FineUI;
using SysManage.BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using ZHDJ.Core;
using ZHDJ.Data.Models.Common;
using ZHDJ.WebPage;

namespace SysManage.Module.Article
{
    public partial class PartyArticleManageList : PageBase
    {
        private DataSet DataSource
        {
            get
            {
                return PartyArticle.GetPartyArticleGridData(Grid1.PageIndex, Grid1.PageSize, this.ArticleModule, this.Category, txtTitle.Text.Trim(), cBranchID);
            }
        }

        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "PartyArticleView";
            }
        }

        public string ArticleModule
        {
            get
            {
                return this.Request["module"] ?? "";
            }
        }

        public string Category
        {
            get { return this.Request["Category"] ?? ""; }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        string cBranchID = "";

        #region 数据加载
        private void LoadData()
        {
            // 权限检查
            CheckPowerWithButton("PartyArticleAdd", btnAdd);

            btnAdd.OnClientClick = Dialog.GetShowReference("PartyArticleManageEdit.aspx?module=" + ArticleModule + "&Category=" + this.Category, "新增文章");

            // 每页记录数
            Grid1.PageSize = ConfigHelper.PageSize;

            if (this.ArticleModule != SysEnum.ArticleModule.PartyBuildingWork.ToString())
            {
                if (this.ArticleModule != SysEnum.ArticleModule.ThreeAffairOpen.ToString())
                    Grid1.Columns[3].Hidden = true;
            }
            BindGrid();
        }

        private void BindGrid()
        {
            //IQueryable<PartyArticle> q = DB.PartyArticles.Where(t => t.Module == ArticleModule);

            //// 在文章标题中搜索
            //string title = txtTitle.Text.Trim();
            //if (!string.IsNullOrEmpty(title))
            //{
            //    q = q.Where(t => t.Title.Contains(title));
            //}
            //if (!string.IsNullOrEmpty(ppBranch.Value))
            //{
            //    q = q.Where(t => t.BranchID == ppBranch.Value);
            //}

            //// 在查询添加之后，排序和分页之前获取总记录数
            //Grid1.RecordCount = q.Count();

            //var qq = from e in q
            //         orderby e.Status descending, e.CreateTime descending
            //         select e;
            // 排列和分页


            //组织动态页面,"所属组织"隐藏或不可更改
            if (ArticleModule == "Organizational" || ArticleModule == "WomenAndChildrenHome" || ArticleModule == "YouthMien" || ArticleModule == "UnionHome")
            {
                //ppBranch.Value = this.CurrentUser.BranchID;//获取当前组织ID
                //ppBranch.Text = ControlBusiness.GetBranchPickerText(this.CurrentUser.BranchID);//获取当前组织名称
                //ppBranch.Enabled = false;//所属组织文本框不可修改
                ppBranch.Hidden = true;//隐藏"所属组织"
                cBranchID = this.CurrentUser.BranchID;
            }
            else
            {
                cBranchID = ppBranch.Value;
            }

            Grid1.RecordCount = Convert.ToInt32(DataSource.Tables[1].Rows[0][0]);
            Grid1.DataSource = DataSource.Tables[0];
            Grid1.DataBind();
        }

        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerWithWindowField("PartyArticleEdit", Grid1, "editField");
            CheckPowerWithLinkButtonField("PartyArticleDelete", Grid1, "deleteField");
        }

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }

        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);
            BindGrid();
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string PartyArticleId = GetSelectedDataKeyID(Grid1);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!CheckPower("PartyArticleDelete"))
                {
                    CheckPowerFailWithAlert();
                    return;
                }

                var del = DB.PartyArticles.FirstOrDefault(t => t.ID == PartyArticleId);
                DB.PartyArticles.Remove(del);
                DB.SaveChanges();
                BindGrid();
            }
        }

        public static string GetBranchName(string branchId)
        {
            return ControlBusiness.GetBranchPickerText(branchId);
        }

        public string GetCategory(string category)
        {
            DataTable dt = PartyArticle.GetCategory("ZHDJ.Article." + this.ArticleModule);
            if (dt.Rows.Count > 0)
            {
                DataRow dataRow = dt.Select("DDicMember='" + category + "'")[0];
                return Convert.ToString(dataRow["DDicMemberName"]);
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 按钮事件
        protected void ppBranch_TextChanged(object sender, EventArgs e)
        {
            ppBranch.ShowTrigger1 = !string.IsNullOrEmpty(ppBranch.Text);
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("PartyArticleDelete"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<string> ids = GetSelectedDataKeyIDs(Grid1);

            // 执行数据库操作
            DB.PartyArticles.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => DB.PartyArticles.Remove(u));
            DB.SaveChanges();

            // 重新绑定表格
            BindGrid();
        }

        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion

        protected void Dialog_Close(object sender, EventArgs e)
        {
            BindGrid();
        }
    }
}